﻿using IDEAMS.core;
using IDEAMS.utils;
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IDEAMS.model
{
    public class DeviceInfoCollection : SHCollection<DeviceInfo>
    {
        private static ILog logger = LogManager.GetLogger(typeof(DeviceInfoCollection));

        public DeviceInfoCollection() { }

        public DeviceInfoCollection(DeviceInfoCollection collection)
        {
            collection.ForEach(x => {
                DeviceInfo data = new DeviceInfo(x);
                dataList.Add(data);
                return false;
            });
        }

        public override bool Equals(DeviceInfo obj, object key)
        {
            return (string)key == obj.serialNo;
        }

        public override void CopyTo(DeviceInfo src, DeviceInfo dst)
        {
            dst.Copy(src);
        }

        public DeviceInfoCollection Clone()
        {
            return new DeviceInfoCollection(this);
        }

        public bool Save()
        {
            bool rn = true;
            rwLock.EnterReadLock();
            try
            {
                string dataFile = TW_App.fileManager.deviceInfoCollectionFile;
                rn = XmlUtil.Save<DeviceInfoCollection>(dataFile, this);
            }
            finally
            {
                rwLock.ExitReadLock();
            }
            return rn;
        }

        public int Load()
        {
            int rn = -1;
            rwLock.EnterWriteLock();
            try
            {
                string dataFile = TW_App.fileManager.deviceInfoCollectionFile;
                bool existsFlag = File.Exists(dataFile);
                if (!existsFlag)
                {
                    logger.WarnFormat("设备文件[{0}]不存在", dataFile);
                    return -2;
                }

                DeviceInfoCollection collection = XmlUtil.Load<DeviceInfoCollection>(dataFile);
                if(collection != null)
                {
                    dataList.Clear();
                    collection.ForEach(x =>
                    {
                        DeviceInfo data = x.Clone();
                        dataList.Add(data);

                        return false;
                    });
                    rn = 0;
                }
                else
                {
                    logger.ErrorFormat("加载设备[{0}]失败", dataFile);
                    rn = -1;
                }
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
            return rn;
        }
    }
}
